//
//  ChatTableViewController.m
//  WChat
//
//  Created by lw on 2018/7/28.
//  Copyright © 2018年 mjsfax. All rights reserved.
//

#import "ChatTableViewController.h"
#import "ChatViewController.h"

NSString * const ChatTitleNormal = @"微信";
NSString * const ChatTitleWillConnect = @"连接中...";
NSString * const ChatTitleDisconnect = @"微信(未连接)";
NSString * const ChatTitleWillReceiveMsg = @"收取中...";

@interface ChatTableViewController ()<EMChatManagerDelegate, IChatManagerDelegate>
@property (strong, nonatomic) NSMutableArray *conversations;
@end

@implementation ChatTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.title = ChatTitleNormal;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([self class])];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    if (!self.conversations.count) {
        [self queryConversationList];
    }
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSInteger *unreadCount = [[EaseMob sharedInstance].chatManager loadTotalUnreadMessagesCountFromDatabase];
    if (unreadCount) {
        self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%zd",unreadCount];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (void)queryConversationList {
    [self.conversations removeAllObjects];
    NSArray *array = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];//yes取出同时存入内存
    [self.conversations addObjectsFromArray:array];
}

#pragma mark - delegate saseMob
//会话列表更新回调
- (void)didUpdateConversationList:(NSArray *)conversationList {
    [self queryConversationList];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.conversations.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([self class]) forIndexPath:indexPath];
    EMConversation *conversation = [self.conversations objectAtIndex:indexPath.row];
    cell.textLabel.text = conversation.chatter;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ChatViewController *chat = [[ChatViewController alloc] init];
    EMConversation *con = [self.conversations objectAtIndex:indexPath.row];
    chat.username = con.chatter;
    [self.navigationController pushViewController:chat animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - easeMob delegate
//即将重联
- (void)willAutoReconnect {
    self.title = ChatTitleWillConnect;
}

- (void)didAutoReconnectFinishedWithError:(NSError *)error {
    if (error) {
        NSLog(@"%@",error);
        self.title = ChatTitleDisconnect;
    } else {
        self.title = ChatTitleNormal;
    }
}

//连接状态改变
- (void)didConnectionStateChanged:(EMConnectionState)connectionState {
    switch (connectionState) {
        case eEMConnectionConnected:{
            self.title = ChatTitleNormal;
            break;
        }
        case eEMConnectionDisconnected:{
            self.title = ChatTitleDisconnect;
            break;
        }
        default:
            break;
    }
}

- (NSMutableArray *)conversations {
    if (!_conversations) {
        _conversations = [NSMutableArray array];
        NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
        [_conversations addObjectsFromArray:conversations];
    }
    return _conversations;
}

@end
